#include "xparameters.h"
#include "xgpio.h"
#include "stdio.h"
#include "xstatus.h"

#define OP_BAR0  XPAR_AXI_BRAM_CTRL_0_S_AXI_BASEADDR
#define OP_BAR1  XPAR_AXI_BRAM_CTRL_1_S_AXI_BASEADDR

XGpio GpioInput;

int exp_config(u32 config_data);

int read_config() {
	int Status;
	u32 Dat_0;
	u32 *wr_buf;

	wr_buf = (u32 *) (OP_BAR0 + 0x120);     // bar0 ram + 72 word
	/*
	 * Initialize the GPIO driver so that it's ready to use,
	 * specify the device ID that is generated in xparameters.h
	 */
	Status = XGpio_Initialize(&GpioInput, XPAR_AXI_GPIO_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Set the direction for all signals to be inputs
	 */
	XGpio_SetDataDirection(&GpioInput, 1, 0xFFFFFFFF);      // gpio
	XGpio_SetDataDirection(&GpioInput, 2, 0xFFFFFFFF);      // gpio2
	/*
	 * Read the state of the data so that it can be  verified
	 */
	Dat_0 = XGpio_DiscreteRead(&GpioInput, 1);
	xil_printf("Cpu 0_config :0x%x\r\n", Dat_0);

	*wr_buf = Dat_0;

	xil_printf("---------Cpu_0 config---------- \r\n");
	exp_config(Dat_0);
	xil_printf("------------------------------ \r\n");

	// *wr_buf++;

	Dat_0 = XGpio_DiscreteRead(&GpioInput, 2);
	xil_printf("Cpu x_config :0x%x\r\n", Dat_0);

	*(wr_buf + 1) = Dat_0;

	xil_printf("---------Cpu_x config---------- \r\n");
	exp_config(Dat_0);
	xil_printf("------------------------------ \r\n");
	return 0;
}

int exp_config(u32 config_data) {
	u32 temp;
	temp = config_data & 0x7;
	switch (temp) {
	case 0b000:
		xil_printf("Cpu Flash boot \r\n");
		break;
	case 0b001:
		xil_printf("Cpu Spi boot \r\n");
		break;
	case 0b010:
		xil_printf("Cpu Lpc boot \r\n");
		break;
	case 0b100:
		xil_printf("Cpu Pcie boot \r\n");
		break;
	case 0b101:
		xil_printf("Cpu 0 RapidIO boot \r\n");
		break;
	}
	temp = (config_data & 0x20) >> 5;
	if (temp == 1)
		xil_printf("Cpu Pcie rc \r\n");
	else
		xil_printf("Cpu Pcie ep \r\n");

	temp = (config_data & 0x300) >> 8;
	switch (temp) {
	case 0b00:
		xil_printf("Cpu RapidIO 2.5G \r\n");
		break;
	case 0b01:
		xil_printf("Cpu RapidIO 3.125G \r\n");
		break;
	case 0b10:
		xil_printf("Cpu RapidIO 5G \r\n");
		break;
	case 0b11:
		xil_printf("Cpu RapidIO 6.25G \r\n");
		break;
	}

	temp = (config_data & 0x1e0000) >> 17;
	switch (temp) {
	case 0b0001:
		xil_printf("Cpu DSP/RASP_clk 500MHz \r\n");
		break;
	case 0b0110:
		xil_printf("Cpu DSP/RASP_clk 800MHz  \r\n");
		break;
	case 0b1010:
		xil_printf("Cpu DSP/RASP_clk 1GHz \r\n");
		break;
	}

	temp = (config_data & 0xe00000) >> 21;
	switch (temp) {
	case 0b010:
		xil_printf("Cpu Ace_clk 500MHz \r\n");
		break;
	}

	temp = (config_data & 0x7000000) >> 24;
	switch (temp) {
	case 0b000:
		xil_printf("Cpu DDR3 800M \r\n");
		break;
	case 0b001:
		xil_printf("Cpu DDR3 1066M \r\n");
		break;
	}

	temp = (config_data & 0x38000000) >> 27;
	switch (temp) {
	case 0b001:
		xil_printf("Cpu axi_clk 400M \r\n");
		break;
	case 0b100:
		xil_printf("Cpu axi_clk 600M \r\n");
		break;
	}
	return XST_SUCCESS;
}
